
import router from '@/router';
import {Message} from 'element-ui';

import {get, post} from "@/config/request.js";
import {sys, permission} from "@/config/api.js";
import {token, storage} from "@/utils/tools.js";

var state = {
    // 是否关闭导航菜单
    isCollapse: false,

    // 用户权限列表
    permissionList: [
      // {
      //   name: 'home',
      //   path: '/home',
      //   component: "home/index",
      //   meta: {
      //     keepAlive: true,
      //     title: '首页',
      //     icon: 'el-icon-s-home',
      //   }
      // },
      // {
      //   name: 'system',
      //   path: '/system',
      //   meta: {
      //     keepAlive: false,
      //     title: '系统管理',
      //     icon: 'el-icon-s-tools'
      //   },
      //   children: [
      //     {
      //       name: 'system-user',
      //       path: '/system/user',
      //       component: "system/user",
      //       meta: {
      //         keepAlive: false,
      //         title: '用户管理',
      //       }
      //     },
      //     {
      //       name: 'system-role',
      //       path: '/system/role',
      //       component: "system/role",
      //       meta: {
      //         keepAlive: false,
      //         title: '角色管理',
      //       }
      //     },
      //     {
      //       name: 'system-menu',
      //       path: '/system/menu',
      //       component: "system/menu",
      //       meta: {
      //         keepAlive: false,
      //         title: '菜单管理',
      //       }
      //     },
      //   ]
      // }
    ],
}

var getters = {
  // 获取用户权限列表
  GET_PERMISSIONLIST: state => {
    var list = state.permissionList;
    if (!list || !list.length) {
      list = storage.get('permissionList');
      state.permissionList = list;
    }
    return list;
  }
}

var mutations = {
  // 设置用户权限列表
  SET_PERMISSIONLIST: (state, permissionList) => {
    state.permissionList = permissionList
  },
}

var actions = {
  // 登出
  Logout ({commit, state}) {
    post(sys.logout).then(() => {
      Message.success('登出成功!');
      // 清除缓存
      storage.remove();
      // 登录
      router.push('/login');
    })
  },

  // 获取用户权限列表
  GetPermissionList ({commit, state}) {
    return new Promise((resolve, reject) => {
      var param = {
        token: token.get()
      }
      get(permission.getUserPermissionByToken, param).then(res => {
        var result = res.result;
        var allAuth = result.allAuth, auth = result.auth, menu = result.menu;
        if (menu && menu.length) {
          storage.set('permissionList', menu);
          commit('SET_PERMISSIONLIST', menu);
          resolve(menu);
        } else {
          reject('该用户没有权限列表，请联系管理员');
        }
      })
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}